﻿using Jint.Native;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
using MongoDB.Bson;

namespace jsweb
{
   public class db
   {
      private MongoServer _server;
      private MongoDatabase _database;
      private Jint.JintEngine _engine;
      private BsonJsonSerializer _jsonSerializer = new BsonJsonSerializer();

      public db(Jint.JintEngine engine)
      {
         _engine = engine;
         _engine.Run("function ObjectId(value) { return value; }");
         BsonSerializer.RegisterSerializer(typeof(JsObject), _jsonSerializer);
      }

      public void use(string database)
      {
         _database = _server.GetDatabase(database);
      }

      public string get(string collection, object selector)
      {
         string jsonStr = selector.ToJson();
         QueryDocument query = QueryDocument.Parse(jsonStr) as QueryDocument;
         var mongoCursor = _database[collection].FindAll();
         BsonArray allResults = new BsonArray();
         int index = 0;
         foreach (var bsonDocument in mongoCursor)
         {
            allResults.Add(bsonDocument);
            index++;
         }
         string jsonResult = allResults.ToJson();
         return jsonResult;
      }

      public void open(JsObject connObj)
      {
         string connStr = "mongodb://localhost:27017";
         _server = MongoServer.Create(connStr);
         _server.Connect();
      }

      public object save(string collection, object jsObject)
      {
         string jsonStr = jsObject.ToJson();
         var result = _database[collection].Insert(QueryDocument.Parse(jsonStr));
         return result;
      }
   }
}
